#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
__version__ = '1.0'
"""
    ***********************************
    *  @filename : GQ.py
    *  @Author : wshu
    *  @CodeDate : 2020/4/15 21:42
    *  @Software : PyCharm
    ***********************************
"""

from sqlalchemy.orm import scoped_session
from tornado.ioloop import IOLoop

from db.redis.RedisCli import Redis
from db.rabbitmq.RabbitMQ import Rabbitmq

from conf.config import (redis_ip, redis_port, redis_auth, MQURI)

class G(object):
    _instance = None

    @classmethod
    def getInstance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def __init__(self):
        self.conf = 'conf'      # 数据库配置
        self.utils = 'Utils'    # 数据库连接池管理类，作为惰性连接使用，现改用ORM不考虑
        self._session = None

    @property
    def currentIOloopInstance(self):
        return IOLoop.current()

    @property
    def session(self):
        if self._session is None:
            self._session = scoped_session('UnitymobSession')   # db uri
        return self._session

    @property
    def redis(self):
        return Redis.getInstance(host=redis_ip, port=redis_port, password=redis_auth,
                                   decode_responses=False)

    @property
    def rabbitmq(self):
        """ 自定义rabbitmq """
        return Rabbitmq.getInstance(MQURI)

    # @property
    # def rpc(self):
    #     fb = conf.facebook
    #     return RPCClient(fb.app_id, fb.app_secret, fb.rpc_endpoint)

    def clear(self):
        """ 释放资源 """
        if self._session is not None:
            self._session.remove()
        self._session = None

        del self.rabbitmq.channel